package com.yawn.spock

import spock.lang.Specification


/**
 * <pre>
 * The star-dot `*.' operator
 * The "star-dot" operator is a shortcut operator allowing you to call a method or a property on all elements of a collection:
 * assert [1, 3, 5] == ['a', 'few', 'words']*.size()
 *
 * class Person {
 *     String name
 *     int age
 * }
 * def persons = [new Person(name:'Hugo', age:17), new Person(name:'Sandra',age:19)]
 * assert [17, 19] == persons*.age
 *     </pre>
 * @author yawn
 *     2019/9/5 17:29
 *
 */
class MockSpec extends Specification {
    Publisher publisher = new Publisher()
    def subscriber = Mock(Subscriber)
    def subscriber2 = Mock(Subscriber)

    def setup() {
        publisher.subscribers << subscriber // << is a Groovy shorthand for List.add()
        publisher.subscribers << subscriber2
    }

    def "should send messages to all subscribers"() {
        when:
        publisher.send("hello")

        then:
        verifyAll {
//            1 * subscriber.receive(_)
            1 * subscriber.receive("hello")
            1 * subscriber2.receive(!"world")
//            1 * subscriber2.receive(_ as String)
        }
    }

}

class Publisher {
    List<Subscriber> subscribers = []
    int messageCount = 0
    void send(String message) {
        // *. 分别调用list每个元素的receive方法
        subscribers*.receive(message)
        messageCount++
    }
}

interface Subscriber {
    void receive(String message)
}


